package com.zzl.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzl.springboot.entity.User;
import com.zzl.springboot.entity.UserVol;
import com.zzl.springboot.entity.Vol;
import com.zzl.springboot.mapper.UserVolMapper;
import com.zzl.springboot.mapper.VolMapper;
import com.zzl.springboot.service.VolService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: AAAzzl
 * @description:
 * @author: zzl
 * @create: 2022-11-30 23:00
 * @version:1.0
 **/

@Service
public class VolServiceImpl implements VolService {

    @Resource
    private VolMapper volMapper;
    @Resource
    private UserVolMapper userVolMapper;

    @Override
    public int setVolInfo(Vol vol) {
        return volMapper.insert(vol);
    }

    @Override
    public PageInfo<Vol> getVolList(int pageNum, int pageSize) {
        //开始分页     后面的第一条查询语句才会被分页处理
        PageHelper.startPage(pageNum, pageSize);
        List<Vol> vol = volMapper.selectAll();
        return new PageInfo<>(vol);
    }

    @Override
    @Transactional
    public Integer setVolUser(Vol vol) {
        // 获取旧数据 将数据锁定  悲观锁
        Vol oldVol = volMapper.selectById(vol.getId());
        // 保存用户id
        Integer userId = vol.getUserMaster();
        // 判断是否已经有负责人
        if (oldVol.getUserMaster()!=0){
            vol.setUserMaster(0);
        }
        // 进行数据更新操作
        if (oldVol.getState()<oldVol.getUserNeed()){
            int i = volMapper.updateVol(vol);
            if (i!=0){
                int i1 = volMapper.setVolUser(vol.getId(), userId);
            }
            return i;
        }

        return 0;
    }

    @Override
    public UserVol selectVolUser(Integer volId, Integer userId) {
        return volMapper.selectVolUser(volId,userId);
    }

    @Override
    public List<Vol> selectByUserId(Integer id) {
        return volMapper.selectByUserId(id);
    }

    @Override
    public List<UserVol> selectVolUserByUserId(Integer id) {
        return userVolMapper.selectByUserId(id);
    }

    @Override
    public Integer commitVol(Integer id) {
        Integer i = userVolMapper.updateUserVolState(id);
        System.out.println("受影响的行数："+i);
        return userVolMapper.updateByVolId(id);
    }
}
